package com.zlzxm.zutil.glide;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;

import androidx.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import java.security.MessageDigest;

/**
 * Created by zlz on 2018/8/7.
 *
 */

public class RoundImageTransformation extends BitmapTransformation {

    private static final String TAG = "RoundImage";

    private  int mBound = 0;

    private  int mBoundColor = 0;

    public RoundImageTransformation( int bound,int color) {

        this.mBound = bound;

        this.mBoundColor = color;
    }





    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {

        return roundCrop(pool,toTransform);
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

    }


    private Bitmap roundCrop(BitmapPool pool, Bitmap source)
    {

        if (source == null)
            return null;


        int size = Math.min(source.getHeight(),source.getWidth()) ;

        Bitmap result = pool.get(size , size , Bitmap.Config.ARGB_8888);


        if (result == null) {

            result = Bitmap.createBitmap(size ,  mBound , Bitmap.Config.ARGB_8888);
        }

        int x = (source.getWidth()  - size ) /2;
        int y = (source.getHeight()  - size ) /2;


        Bitmap target = Bitmap.createBitmap(source,x,y,size,size);

        Canvas canvas = new Canvas(result);

        Paint paint = new Paint();
        paint.setShader(new BitmapShader(target, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        canvas.drawCircle(size/2, size/2, size/2, paint);

        paint.reset();
        paint.setAntiAlias(true);
        paint.setColor(mBoundColor);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(mBound);
        canvas.drawCircle(size /2 , size/2, (size - mBound)/2, paint);

        return result;
    }


}